package com.cn.happymall.controller.portal;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cn.happymall.bean.MmallUser;
import com.cn.happymall.common.Constant;
import com.cn.happymall.common.ServerResponse;
import com.cn.happymall.service.UserService;

/**
 * @ClassName UserController
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hasee
 * @Date 2017年12月25日 下午2:28:22
 * @version 1.0.0
 */
@Controller
@RequestMapping("/user/")
public class UserController {

	@Autowired
	private UserService service;

	@RequestMapping(value = "/login.do", method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse login(HttpSession session, String username, String password) {
		MmallUser user = service.login(username, password);
		if (user == null) {
			return ServerResponse.createFailure("用户名或密码错误");
		}
		session.setAttribute(Constant.SESSION_STATUS, user);

		//清空密码
		user.setPassword(null);

		return ServerResponse.createSuccess(user);
	}

	@RequestMapping(value = "/register.do", method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse register(MmallUser user) {

		int i = service.register(user);

		if (i != 0) {
			return ServerResponse.createSuccess("注册成功");
		}

		return ServerResponse.createFailure("注册失败");
	}

	@RequestMapping(value = "/check_valid.do", method = RequestMethod.POST)
	@ResponseBody
	public ServerResponse check(String str, String type) {

		int nameOrEmail = service.checkNameOrEmail(str, type);

		if (nameOrEmail >= 1 && type.equals("email")) {
			return ServerResponse.createFailure("邮箱已存在");
		}
		if (nameOrEmail == 0 && type.equals("email")) {
			return ServerResponse.createSuccess("邮箱可用");
		}

		if (nameOrEmail >= 1 && type.equals("username")) {
			return ServerResponse.createFailure("用户名已存在");
		}

		if (nameOrEmail == 0 && type.equals("username")) {
			return ServerResponse.createSuccess("用户名可用");
		}

		return null;
	}

}
